package jim.h.common.android.lib.zxing;

import java.util.Hashtable;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QrcodeUtil {
    
    public static Bitmap createNormalQrImg(String content, int QRCODE_SIZE) throws Exception {
        // 用于设置QR二维码参数
        Hashtable<EncodeHintType, Object> qrParam = new Hashtable<EncodeHintType, Object>();
        // 设置QR二维码的纠错级别——这里选择最高H级别
        qrParam.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 设置编码方式
        qrParam.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                qrParam);

        // 开始利用二维码数据创建Bitmap图片，分别设为黑白两色
        int w = bitMatrix.getWidth();
        int h = bitMatrix.getHeight();
        
        int dx = 0;
        for (int y = 0; y < h; y++) {
            for (int x = 0; x < w; x++) {
                if (bitMatrix.get(x, y)) {
                    dx = y-4;
                    break;
                }
            }
            if(dx > 0) {
                break;
            }
        }
        w = w-2*dx;
        h =  h-2*dx; 
        
        int[] data = new int[w * h];
        for (int y = 0; y < h; y++) {
            for (int x = 0; x < w; x++) {
                if (bitMatrix.get(x+dx, y+dx))
                    data[y * w + x] = 0xff000000;// 黑色
                else
                    data[y * w + x] = -1;// -1 相当于0xffffffff 白色
            }
        }
        // 创建一张bitmap图片，采用最高的图片效果ARGB_8888
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        // 将上面的二维码颜色数组传入，生成图片颜色
        bitmap.setPixels(data, 0, w, 0, 0, w, h);

        return bitmap;
    }

    public static Bitmap createLogoQrImg(String content, int QRCODE_SIZE, Bitmap portrait) throws Exception {
        Bitmap qr = createNormalQrImg(content, QRCODE_SIZE);
        // 头像图片的大小
        int portrait_W = portrait.getWidth();
        int portrait_H = portrait.getHeight();
        // 设置头像要显示的位置，即居中显示
        int left = (qr.getWidth()  - portrait_W) / 2;
        int top = (qr.getHeight() - portrait_H) / 2;
        int right = left + portrait_W;
        int bottom = top + portrait_H;
        Rect rect1 = new Rect(left, top, right, bottom);
        // 取得qr二维码图片上的画笔，即要在二维码图片上绘制我们的头像
        Canvas canvas = new Canvas(qr);
        // 设置我们要绘制的范围大小，也就是头像的大小范围
        Rect rect2 = new Rect(0, 0, portrait_W, portrait_H);
        // 开始绘制
        canvas.drawBitmap(portrait, rect2, rect1, null);
        return qr;
    }

    public static String decodeQrImg(Bitmap bmp) throws Exception {
        QRCodeReader reader = new QRCodeReader();
        // 用于设置QR二维码参数
        Hashtable<DecodeHintType, Object> qrParam = new Hashtable<DecodeHintType, Object>();
        // 设置编码方式
        qrParam.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        RGBLuminanceSource source = new RGBLuminanceSource(bmp);
        BinaryBitmap bmpM = new BinaryBitmap(new HybridBinarizer(source));
        Result result = reader.decode(bmpM, qrParam);
        return result.getText();
    }

    public static class RGBLuminanceSource extends LuminanceSource {
        private final byte[] luminances;

        private final int dataWidth;

        private final int dataHeight;

        private final int left;

        private final int top;

        public RGBLuminanceSource(Bitmap bitmap) {
            super(bitmap.getWidth(), bitmap.getHeight());
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            int[] pixels = new int[width * height];
            bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

            dataWidth = width;
            dataHeight = height;
            left = 0;
            top = 0;
            // In order to measure pure decoding speed, we convert the entire
            // image to a greyscale array
            // up front, which is the same as the Y channel of the
            // YUVLuminanceSource in the real app.
            luminances = new byte[width * height];
            for (int y = 0; y < height; y++) {
                int offset = y * width;
                for (int x = 0; x < width; x++) {
                    int pixel = pixels[offset + x];
                    int r = (pixel >> 16) & 0xff;
                    int g = (pixel >> 8) & 0xff;
                    int b = pixel & 0xff;
                    if (r == g && g == b) {
                        // Image is already greyscale, so pick any channel.
                        luminances[offset + x] = (byte) r;
                    } else {
                        // Calculate luminance cheaply, favoring green.
                        luminances[offset + x] = (byte) ((r + g + g + b) >> 2);
                    }
                }
            }
        }

        @Override
        public byte[] getMatrix() {
            int width = getWidth();
            int height = getHeight();
            // If the caller asks for the entire underlying image, save the copy
            // and give them the
            // original data. The docs specifically warn that result.length must
            // be ignored.
            if (width == dataWidth && height == dataHeight) {
                return luminances;
            }
            int area = width * height;
            byte[] matrix = new byte[area];
            int inputOffset = top * dataWidth + left;
            // If the width matches the full width of the underlying data,
            // perform a single copy.
            if (width == dataWidth) {
                System.arraycopy(luminances, inputOffset, matrix, 0, area);
                return matrix;
            }
            // Otherwise copy one cropped row at a time.
            byte[] rgb = luminances;
            for (int y = 0; y < height; y++) {
                int outputOffset = y * width;
                System.arraycopy(rgb, inputOffset, matrix, outputOffset, width);
                inputOffset += dataWidth;
            }
            return matrix;

        }

        @Override
        public byte[] getRow(int y, byte[] row) {
            if (y < 0 || y >= getHeight()) {
                throw new IllegalArgumentException("Requested row is outside the image: " + y);
            }
            int width = getWidth();
            if (row == null || row.length < width) {
                row = new byte[width];
            }
            int offset = (y + top) * dataWidth + left;
            System.arraycopy(luminances, offset, row, 0, width);
            return row;
        }
    }
}
